import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { MenuTree } from '~/services/menu.service';
import { authService } from '~/services/auth.service';
import { storage, StorageKey } from '~/utils/storage';

/**
 * 路由状态
 */
interface RouteState {
  // 状态
  menus: MenuTree[];
  isMenusLoaded: boolean;

  // 操作
  loadMenus: () => Promise<void>;
  clearMenus: () => void;
}

/**
 * 路由 Store
 * 管理动态路由和菜单数据
 */
export const useRouteStore = create<RouteState>()(
  persist(
    (set, get) => ({
      // 初始状态
      menus: [],
      isMenusLoaded: false,

      // 加载用户菜单
      loadMenus: async () => {
        // 如果已经加载过，跳过
        if (get().isMenusLoaded) {
          return;
        }

        try {
          const menus = await authService.getMenus();
          storage.set(StorageKey.USER_MENUS, menus);
          set({
            menus,
            isMenusLoaded: true,
          });
        } catch (error) {
          console.error('加载菜单失败:', error);
          throw error;
        }
      },

      // 清除菜单
      clearMenus: () => {
        storage.remove(StorageKey.USER_MENUS);
        set({
          menus: [],
          isMenusLoaded: false,
        });
      },
    }),
    {
      name: 'route-storage',
      partialize: (state) => ({
        menus: state.menus,
        isMenusLoaded: state.isMenusLoaded,
      }),
    }
  )
);

